﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar.SuperGrid;
using System.IO;
using SyncLib.Client;
using AppCommon;
using SyncApplication.Dialog;
using SyncApplication.Business;
using Microsoft.Synchronization;
using log4net;
using SyncLib;
using System.Text.RegularExpressions;
using DevComponents.AdvTree;
using Microsoft.SqlServer.Management.Smo;
using System.Configuration;
using System.Diagnostics;


namespace SyncApplication
{
    public partial class SyncDialog : Form
    {
        static ILog Log = LogManager.GetLogger(typeof(Log4NetImplement));
        static SyncDialog _Current;
        public static SyncDialog Current
        {
            get
            {
                if (_Current == null || _Current.IsDisposed)
                {
                    _Current = new SyncDialog();
                    _Current.Hide();
                }
                return _Current;
            }
            set
            {
                _Current = value;
            }
        }

        public static bool ShowWhenSync { get; set; }
        
        public SyncDialog()
        {
            InitializeComponent();
            Disposed += new EventHandler(SyncDialog_Disposed);
        }

        void SyncDialog_Disposed(object sender, EventArgs e)
        {
            lbUriAnimation.Dispose();
        }


        private void ManualSyncDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                Hide();
                if (ClientSyncContext.IsRunning)
                    FrmNotify.Current.SyncAppNotify.ShowBalloonTip(1000, "Keeper sync", "Quá trình vẫn tiếp tục", ToolTipIcon.Info);
            }


        }
        public void HighlightNode(int rowIndex)
        {
            if (advTree1.InvokeRequired)
            {
                advTree1.Invoke(new MethodInvoker(() => { HighlightNode(rowIndex); }));
                return;
            }
            try
            {
                Node node = advTree1.GetNodeByFlatIndex(rowIndex);
                if (node != null)
                {
                    node.EnsureVisible();
                    FormatNode(node, ClientSyncContext.CurrentTask);
                    advTree1.SelectedNode = node;
                    // node.Invalidate();
                }
                else
                    Debug.WriteLine("Node null-------------------------------------");
            }
            catch
            {
            }
        }
        public void SetImage(int rowIndex, Image image)
        {

            
            if (advTree1.InvokeRequired)
            {
                advTree1.Invoke(new MethodInvoker(() => { SetImage(rowIndex, image); }));
                return;
            }
            if (ClientSyncContext.CurrentTask != null)
                ClientSyncContext.CurrentTask.Image = image;
            try
            {
                Node node = advTree1.GetNodeByFlatIndex(rowIndex);
                if (node != null)
                {
                    node.EnsureVisible();                    
                    advTree1.SelectedNode = node;
                    // node.Invalidate();
                }
                else
                    Debug.WriteLine("Node null-------------------------------------");
            }
            catch
            {
            }


        }
       
        private void btnClose_Click(object sender, EventArgs e)
        {

            Hide();
            if (ClientSyncContext.IsRunning)
                FrmNotify.Current.SyncAppNotify.ShowBalloonTip(1000, "Keeper sync", "Quá trình vẫn tiếp tục", ToolTipIcon.Info);

        }

        private void ManualSyncDialog_Shown(object sender, EventArgs e)
        {
            //FormatConditonTree();
            if (advTree1.DataSource == null)
                advTree1.DataSource = ClientSyncContext.SyncDS.TaskSyncList;

            lbUri.Text = ClientSyncContext.UrlProvider.Url;
            lbUriAnimation.Animation(-1);
        }
        LabelXAnimation lbUriAnimation = null;

        private void ManualSyncDialog_Load(object sender, EventArgs e)
        {


            lbUriAnimation = new LabelXAnimation("");
            lbUriAnimation.Label = lbUri;
            lbUriAnimation.IconPath = Application.StartupPath + "\\Animation\\Labelx";
            lbUriAnimation.LoadIcon();

        }

        public void Begin()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate { Begin(); }));
                return;
            }
            btnStop.Enabled = true;
            RefreshSummary();
            pictureBox1.Visible = false;
            circularProgress1.Visible = true;
            timer1.Enabled = true;
            lbMessage.Text = "Đang thực hiện đồng bộ";
            RefreshSummary();
        }

        public void End(bool isNormal)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate { End(isNormal); }));
                return;
            }
            //advTree1.RefreshItems();
            RefreshSummary();
            btnStop.Enabled = false;
            timer1.Enabled = false;
            if (!isNormal)
                pictureBox1.Image = Properties.Resources.Error;
            else
                pictureBox1.Image = Properties.Resources.accepted;
            pictureBox1.Location = circularProgress1.Location;
            pictureBox1.Visible = true;
            circularProgress1.Visible = false;
            lbMessage.Text = "Kết thúc";
            Regex t = new Regex("[0-9]+");
            Match m = t.Match(lbTaskSuccess.Text);
            string success = m.Value;
            string count = t.Match(lbTaskCount.Text).Value;
            string error = t.Match(lbTaskError.Text).Value;
            string warning = t.Match(lbTaskWarning.Text).Value;

            if ((success == "000" && error == "000" && warning == "000")
                || (int.Parse(warning) + int.Parse(success) + int.Parse(error) < int.Parse(count))
                )
            {
                Log.Info("*********************************************************");
                Log.Info("*********************************************************");
                Log.Info("                  ERROR UI                               ");
                Log.Info("*********************************************************");
                Log.Info("*********************************************************");
                Log.Info("*********************************************************");

            }

        }
        public void DisplayMessage(string msg)
        {
            lbMessage.Invoke(new MethodInvoker(delegate
            {
                lbMessage.Text = msg;
            })); ;
        }

        public void InvokeRefresh()
        {
            this.Invoke(new MethodInvoker(RefreshSummary));

        }
        public void InvokeFinish()
        {
            this.Invoke(new MethodInvoker(delegate
            {
                btnStop.Enabled = false;

            }));
        }
        private void RefreshSummary()
        {

            try
            {
                advTree1.DataSource = ClientSyncContext.SyncDS.TaskSyncList;
                //FormatConditonTree();
                advTree1.SelectedIndex=-1;
                //advTree1.RefreshItems();
            }
            catch
            {

            }
            DisplayTotal(ClientSyncContext.SyncDS.TaskSyncList.Count);
            DisplaySuccess(ClientSyncContext.SyncDS.TaskSyncList.Select("StatusCode='" + ClientConst.TaskSuccess + "'").Length);
            DisplayError(ClientSyncContext.SyncDS.TaskSyncList.Select("StatusCode='" + ClientConst.TaskError + "'").Length);
            DisplayWaring(ClientSyncContext.SyncDS.TaskSyncList.Select("StatusCode='" + ClientConst.TaskWarning + "'").Length);
        }
        private void FormatConditonTree()
        {
            try
            {
                taskError.BackColor = Properties.Settings.Default.ErrorColor;
                taskSuccess.BackColor = Properties.Settings.Default.SuccessColor;
                taskWarning.BackColor = Properties.Settings.Default.WarningColor;
               // taskWarning.BackColor = Color.Yellow;

                for (int i = 0; i < ClientSyncContext.SyncDS.TaskSyncList.Count; i++)
                {
                    Node node = advTree1.GetNodeByFlatIndex(i);
                    if (node != null)
                    {

                        FormatNode(node, ClientSyncContext.SyncDS.TaskSyncList[i]);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
         void FormatNode(Node node, ClientSyncDS.TaskSyncListRow task)
        {             
             
            switch (task.StatusCode)
            {
                case ClientConst.TaskError:
                    node.Style = taskError;
                    //node.StyleSelected = taskError;
                    break;
                case ClientConst.TaskSuccess:
                    node.Style = taskSuccess;
                    //node.StyleSelected = taskSuccess;
                    break;
                case ClientConst.TaskWarning:    
                    node.Style = taskWarning;
                    //node.StyleSelected = taskWarning;
                    break;
                default:
                    node.Style = elementStyle1;
                    break;
            }
        }
        private void DisplayTotal(int msg)
        {
            lbTaskCount.Invoke(new MethodInvoker(delegate
            {
                lbTaskCount.Text = string.Format("Tổng số: {0:0,##}", msg);
            }));
        }
        private void DisplaySuccess(int msg)
        {
            lbTaskSuccess.Invoke(new MethodInvoker(delegate
            {
                lbTaskSuccess.Text = string.Format("Thành công: {0:0,##}", msg);
            }));
        }
        private void DisplayError(int msg)
        {
            lbTaskError.Invoke(new MethodInvoker(delegate
            {
                lbTaskError.Text = string.Format("Lỗi: {0:0,##}", msg);
            }));
        }
        private void DisplayWaring(int msg)
        {
            lbTaskWarning.Invoke(new MethodInvoker(delegate
            {
                lbTaskWarning.Text = string.Format("Cảnh báo: {0:0,##}", msg);
            }));
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            //AnimationTask.Start();
            try
            {
                ClientSyncContext.CancelRemainingSyncTask();
                if (ClientSyncContext.CurrentAgent != null &&
                    (ClientSyncContext.CurrentAgent.State == SyncOrchestratorState.Downloading ||
                    ClientSyncContext.CurrentAgent.State == SyncOrchestratorState.Uploading ||
                    ClientSyncContext.CurrentAgent.State == SyncOrchestratorState.UploadingAndDownloading))
                    ClientSyncContext.CurrentAgent.Cancel();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }



        private void timer1_Tick(object sender, EventArgs e)
        {
            if (circularProgress1.Value >= circularProgress1.Maximum)
                circularProgress1.Value = 0;
            circularProgress1.Value++;
            circularProgress1.IsRunning = true;
        }



        private void btniSyncResultDetail_Click(object sender, EventArgs e)
        {
            //if (GridMain.ActiveRow != null)
            //{
            //    ClientSyncDS.TaskSyncListRow task = GridMain.GetDataRow<ClientSyncDS.TaskSyncListRow>(GridMain.ActiveRow.RowIndex);
            //    DetailSync frm = new DetailSync();
            //    frm.ShowDetail("Ket qua dong bo pham vi " + task.ScopeName, task.Message, task.SessionId);
            //}
        }

        private void GridMain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
                btniSyncResultDetail_Click(sender, null);
            if (e.KeyCode == Keys.F3)
                btniDetailMessage_Click(sender, null);

        }

        private void btniDetailMessage_Click(object sender, EventArgs e)
        {
            if (advTree1.SelectedNode != null && ClientSyncContext.IsRunning == false)
            {
                DetailMessage frm = new DetailMessage();
                ClientSyncDS.TaskSyncListRow row = ClientSyncContext.SyncDS.TaskSyncList[advTree1.Nodes.IndexOf(advTree1.SelectedNode)];
                frm.ShowMessage(row.ScopeName + "[" + row.Status + "]", row.ClientClass + " ==> " + row.Message);
                frm.Dispose();

            }
            //if (GridMain.ActiveRow != null)
            //{
            //    DetailMessage frm = new DetailMessage();
            //    ClientSyncDS.TaskSyncListRow row = GridMain.GetDataRow<ClientSyncDS.TaskSyncListRow>(GridMain.ActiveRow.RowIndex);
            //    frm.ShowMessage(row.ScopeName + "[" + row.Status + "]", row.ClientClass + " ==> " + row.Message);
            //    frm.Dispose();
            //}
        }

        private void ckNotShowWhenAuto_CheckedChanged(object sender, EventArgs e)
        {
           System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           config.AppSettings.Settings["ShowMonitorForm"].Value = ckNotShowWhenAuto.Checked.ToString();
           config.AppSettings.SectionInformation.ForceSave = true;
           config.Save(ConfigurationSaveMode.Modified);
           ShowWhenSync = !ckNotShowWhenAuto.Checked;
        }


    }
    public class KGridImageEditControl : GridImageEditControl
    {

        public override void SetValue(object value)
        {
            if (Image != null && Image.Tag != null && Image.Tag.ToString() == "MS")
                Image.Dispose();
            if (value is Image)
            {
                Image = (Image)value;
            }
            else
                if (value is Byte[])
                {
                    Image = byteArrayToImage((Byte[])value);
                }
                else
                    base.SetValue(value);
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            Image.Tag = "MS";
            return returnImage;
        }
    }
}
